/**g++ -o callpy callpy.cpp -I/usr/include/python2.6 -L/usr/lib64/python2.6/config -lpython2.6**/
//g++ ctest_wen_python.cpp  -o ctest_wen_python -I/usr/include/python2.7/ -lpython2.7 
#include <Python.h>


struct BMC_Ctrl{

	PyObject *pModule;
	PyObject *pFunLoadCfg;
	PyObject *pFunTimerStart;
	PyObject *pFunTimerStop;
	PyObject *pFunPoweronRaid;
	PyObject *pFunFreshAccessTime;
};
/*
void release_BMC_Ctrl(BMC_Ctrl* ctrl){
	PyObject_CallObject(ctrl->pFunTimerStop, NULL);
	Py_DECREF(ctrl->pFunTimerStart);
	Py_DECREF(ctrl->pFunLoadCfg);
	Py_DECREF(ctrl->pFunTimerStop);
	Py_DECREF(ctrl->pFunPoweronRaid);
	Py_DECREF(ctrl->pModule);

};
*/
struct BMC_Ctrl* init_BMC_Ctrl(){
	static struct BMC_Ctrl ctrl={NULL,NULL,NULL,NULL,NULL,NULL};
	if(ctrl.pModule != NULL){
		return &ctrl;
	}
	printf("BMC_Ctrl init\n");
	Py_Initialize();
	if(!Py_IsInitialized()){return NULL;}
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('.')");
	if(NULL == (ctrl.pModule=PyImport_ImportModule("bmc_ctrl"))){
		printf("Can't find bmc_ctrl.py\n");
		return NULL;
	}
	//获取待调用函数名
	if(!(ctrl.pFunLoadCfg=PyObject_GetAttrString(ctrl.pModule, "bmc_ctrl_load_cfg"))){
		printf("Can't find fun bmc_ctrl_load_cfg");
		return NULL;
	}
	if(!(ctrl.pFunTimerStart=PyObject_GetAttrString(ctrl.pModule, "timer_bmc_sart_all"))){
		printf("Can't find fun timer_bmc_sart_all");
		return NULL;
	}
	if(!(ctrl.pFunTimerStop=PyObject_GetAttrString(ctrl.pModule, "timer_bmc_stop_all"))){
		printf("Can't find fun timer_bmc_stop_all");
		return NULL;
	}
	if(!(ctrl.pFunPoweronRaid=PyObject_GetAttrString(ctrl.pModule, "bmc_active_raid"))){
		printf("Can't find fun bmc_poweroff_raid");
		return NULL;
	}
	if(!(ctrl.pFunFreshAccessTime=PyObject_GetAttrString(ctrl.pModule, "bmc_fresh_access_time"))){
		printf("Can't find fun bmc_fresh_access_time");
		return NULL;
	}
	PyObject_CallObject(ctrl.pFunLoadCfg, NULL);
	PyObject_CallObject(ctrl.pFunTimerStart, NULL);
	return &ctrl;

};
	
void fresh_BMC_RAID_AccessTime(const char* filename){
	PyObject *args=NULL;
	args =  PyTuple_New(1);
	PyTuple_SetItem(args, 0, Py_BuildValue("s",filename));
	struct BMC_Ctrl* ctrl = init_BMC_Ctrl();
	if(ctrl != NULL){
		PyObject_CallObject(ctrl->pFunFreshAccessTime, args);
	}
	Py_DECREF(args);
};
int poweronRaid(const char* filename){
	PyObject *result=NULL;
	PyObject *args=NULL;
	struct BMC_Ctrl* ctrl = init_BMC_Ctrl();
	if(ctrl == NULL){
		return 1;
	}
	args =  PyTuple_New(1);
	printf("11111111111\n");
	PyTuple_SetItem(args, 0, Py_BuildValue("s",filename));
	printf("222222222\n");
	result = PyObject_CallObject(ctrl->pFunPoweronRaid, args);
	printf("33333333\n");
	int resultLong = PyInt_AsLong(result);
	//Py_DECREF(result);
	Py_DECREF(args);
	return resultLong;
};

int main(int argc, char**  argv)
{
	fresh_BMC_RAID_AccessTime("raid0_2");
	fresh_BMC_RAID_AccessTime("/raid0_1/filename");
	printf("poweron %d\n",poweronRaid("/raid/00/1"));
	return 0;
};
